package com.hackordie.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/admin")
public class AdminController extends AMainController {

	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
	public String login(ModelMap model, HttpServletRequest request) throws Exception {
		breadCrumbService.addNode("Admin", 0, request);
		return "admin/dashboard";
	}

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public String users(ModelMap model, HttpServletRequest request) throws Exception {
		breadCrumbService.addNode("User Management", 1, request);
		return "redirect:/admin/users/pages/1";
	}

	@RequestMapping(value = "/users/pages/{page}", method = RequestMethod.GET)
	public String page(@PathVariable("page") int page, ModelMap model, HttpServletRequest request) throws Exception {
		breadCrumbService.addNode("Page " + page, 2, request);

		int PAGE_FIELDS = 10;
		int pages = (int) Math.ceil((double) hodManager.countAllUsers() / (double) PAGE_FIELDS);
		int begin = Math.max(1, page - 5);
		int end = Math.min(begin + 10, pages);

		model.addAttribute("totalPages", pages);
		model.addAttribute("beginIndex", begin);
		model.addAttribute("endIndex", end);
		model.addAttribute("currentIndex", page);

		int first = (page - 1) * PAGE_FIELDS;

		model.addAttribute("users", hodManager.getAllUsersByRange(first, PAGE_FIELDS));
		model.addAttribute("active_users", "active");
		return "admin/users";
	}

	@RequestMapping(value = "/users/delete/{idUser}", method = RequestMethod.GET)
	public String usersdelete(@PathVariable("idUser") int idUser, ModelMap model) throws Exception {
		hodManager.deleteUser(idUser);
		return "redirect:/admin/users/pages/1";
	}

	@RequestMapping(value = "/users/block/{idUser}", method = RequestMethod.GET)
	public String usersblock(@PathVariable("idUser") int idUser, ModelMap model) throws Exception {
		hodManager.disableUser(idUser);
		return "redirect:/admin/users/pages/1";
	}

	@RequestMapping(value = "/roles", method = RequestMethod.GET)
	public String roles(ModelMap model, HttpServletRequest request) throws Exception {
		breadCrumbService.addNode("Roles Management", 1, request);
		model.addAttribute("active_roles", "active");
		return "admin/roles";
	}

}
